<script>
  var replaceWords = function (dictionary, sentence) {
    // 按字母长度排列
    dictionary.sort((a,b)=>a.length-b.length);
    const words = sentence.split(' ');
    for (let i = 0; i < words.length; i++) {
      const word = words[i];
      // 找前缀最先符合的
      for (let j = 0; j < dictionary.length; j++) {
        const f = dictionary[j];
        if(new RegExp(`^${f}`).test(word)){
          words[i] = f;
          break;
        }
      }
    }
    return words.join(" ");
  };
  console.log(replaceWords(["catt","cat","bat","rat"], "the cattle was rattled by the battery"));
</script>